import messaging from '@react-native-firebase/messaging';
import { Platform, Alert, PermissionsAndroid } from 'react-native';
import StorageUtil from './StorageUtil';

class FCMUtil {
  constructor() {
    this.isInitialized = false;
    this.fcmToken = null;
    this.messageHandlers = [];
    this.notificationHandlers = [];
  }

  /**
   * 初始化FCM
   */
  async initialize() {
    try {
      // 请求通知权限
      const hasPermission = await this.requestPermission();
      if (!hasPermission) {
        console.warn('FCM: 通知权限被拒绝');
        return false;
      }

      // 获取FCM Token
      await this.getFCMToken();

      // 设置消息监听器
      this.setupMessageListeners();

      // 处理应用被杀死时的通知点击
      this.handleInitialNotification();

      this.isInitialized = true;
      console.log('FCM: 初始化成功');
      return true;
    } catch (error) {
      console.error('FCM: 初始化失败', error);
      return false;
    }
  }

  /**
   * 请求通知权限
   */
  async requestPermission() {
    try {
      if (Platform.OS === 'android') {
        // Android 13+ 需要请求通知权限
        if (Platform.Version >= 33) {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
          );
          return granted === PermissionsAndroid.RESULTS.GRANTED;
        }
        return true;
      } else {
        // iOS权限请求
        const authStatus = await messaging().requestPermission({
          alert: true,
          announcement: false,
          badge: true,
          carPlay: false,
          provisional: false,
          sound: true,
        });

        return (
          authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
          authStatus === messaging.AuthorizationStatus.PROVISIONAL
        );
      }
    } catch (error) {
      console.error('FCM: 权限请求失败', error);
      return false;
    }
  }

  /**
   * 获取FCM Token
   */
  async getFCMToken() {
    try {
      const token = await messaging().getToken();
      this.fcmToken = token;
      
      // 保存token到本地存储
      await StorageUtil.setItem('fcm_token', token);
      
      console.log('FCM Token:', token);
      return token;
    } catch (error) {
      console.error('FCM: 获取Token失败', error);
      return null;
    }
  }

  /**
   * 设置消息监听器
   */
  setupMessageListeners() {
    // 前台消息监听
    messaging().onMessage(async remoteMessage => {
      console.log('FCM: 收到前台消息', remoteMessage);
      this.handleMessage(remoteMessage, 'foreground');
    });

    // 后台消息监听（应用在后台但未被杀死）
    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log('FCM: 从后台通知打开应用', remoteMessage);
      this.handleNotificationOpen(remoteMessage, 'background');
    });

    // Token刷新监听
    messaging().onTokenRefresh(token => {
      console.log('FCM: Token刷新', token);
      this.fcmToken = token;
      StorageUtil.setItem('fcm_token', token);
      this.notifyTokenRefresh(token);
    });
  }

  /**
   * 处理应用被杀死时的通知点击
   */
  async handleInitialNotification() {
    const remoteMessage = await messaging().getInitialNotification();
    if (remoteMessage) {
      console.log('FCM: 从杀死状态通知打开应用', remoteMessage);
      this.handleNotificationOpen(remoteMessage, 'killed');
    }
  }

  /**
   * 处理收到的消息
   */
  handleMessage(remoteMessage, state) {
    const messageData = {
      messageId: remoteMessage.messageId,
      data: remoteMessage.data,
      notification: remoteMessage.notification,
      from: remoteMessage.from,
      sentTime: remoteMessage.sentTime,
      ttl: remoteMessage.ttl,
      state: state // 'foreground', 'background', 'killed'
    };

    // 通知所有消息处理器
    this.messageHandlers.forEach(handler => {
      try {
        handler(messageData);
      } catch (error) {
        console.error('FCM: 消息处理器错误', error);
      }
    });

    // 如果是前台消息，显示本地通知
    if (state === 'foreground' && remoteMessage.notification) {
      this.showLocalNotification(remoteMessage.notification);
    }
  }

  /**
   * 处理通知点击
   */
  handleNotificationOpen(remoteMessage, state) {
    const notificationData = {
      messageId: remoteMessage.messageId,
      data: remoteMessage.data,
      notification: remoteMessage.notification,
      state: state
    };

    // 通知所有通知处理器
    this.notificationHandlers.forEach(handler => {
      try {
        handler(notificationData);
      } catch (error) {
        console.error('FCM: 通知处理器错误', error);
      }
    });
  }

  /**
   * 显示本地通知（前台时）
   */
  showLocalNotification(notification) {
    if (Platform.OS === 'ios') {
      Alert.alert(
        notification.title || '新消息',
        notification.body || '',
        [
          { text: '确定', style: 'default' }
        ]
      );
    }
    // Android会自动显示通知
  }

  /**
   * 添加消息处理器
   */
  addMessageHandler(handler) {
    if (typeof handler === 'function') {
      this.messageHandlers.push(handler);
    }
  }

  /**
   * 移除消息处理器
   */
  removeMessageHandler(handler) {
    const index = this.messageHandlers.indexOf(handler);
    if (index > -1) {
      this.messageHandlers.splice(index, 1);
    }
  }

  /**
   * 添加通知点击处理器
   */
  addNotificationHandler(handler) {
    if (typeof handler === 'function') {
      this.notificationHandlers.push(handler);
    }
  }

  /**
   * 移除通知点击处理器
   */
  removeNotificationHandler(handler) {
    const index = this.notificationHandlers.indexOf(handler);
    if (index > -1) {
      this.notificationHandlers.splice(index, 1);
    }
  }

  /**
   * 通知Token刷新
   */
  notifyTokenRefresh(token) {
    // 可以在这里调用API更新服务器上的token
    console.log('FCM: 需要更新服务器Token', token);
  }

  /**
   * 订阅主题
   */
  async subscribeToTopic(topic) {
    try {
      await messaging().subscribeToTopic(topic);
      console.log(`FCM: 订阅主题成功 - ${topic}`);
      return true;
    } catch (error) {
      console.error(`FCM: 订阅主题失败 - ${topic}`, error);
      return false;
    }
  }

  /**
   * 取消订阅主题
   */
  async unsubscribeFromTopic(topic) {
    try {
      await messaging().unsubscribeFromTopic(topic);
      console.log(`FCM: 取消订阅主题成功 - ${topic}`);
      return true;
    } catch (error) {
      console.error(`FCM: 取消订阅主题失败 - ${topic}`, error);
      return false;
    }
  }

  /**
   * 获取当前FCM Token
   */
  getCurrentToken() {
    return this.fcmToken;
  }

  /**
   * 检查是否已初始化
   */
  isReady() {
    return this.isInitialized;
  }

  /**
   * 清理资源
   */
  cleanup() {
    this.messageHandlers = [];
    this.notificationHandlers = [];
    this.isInitialized = false;
    this.fcmToken = null;
  }
}

// 创建单例实例
const fcmUtil = new FCMUtil();

export default fcmUtil;